package com.api.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 发送post请求
 * 
 * @author Administrator
 *
 */
public class PostMethod {

	/**
	 * POST方法提交
	 */
	public static String sendPost(String url, String parameter, String cookies) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";

		try {
			URL realurl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) realurl.openConnection();

			if ("" != cookies) {
				conn.setRequestProperty("Cookie", cookies);
			}

			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			out = new PrintWriter(conn.getOutputStream());
			out.print(parameter);
			Thread.sleep(1000);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

}
